package com.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
import java.util.List;

public class MyWatcher1 {

    private static final String CONNECTADDRESS="192.168.1.120";
    private static final int SESSIONTIME=50*1000;
    private static final String PATH="/t1";
    private static ZooKeeper zk;

    public static ZooKeeper getZk() {
        return zk;
    }

    public static void setZk(ZooKeeper zk) {
        MyWatcher1.zk = zk;
    }

    public ZooKeeper start() throws Exception {
           return new ZooKeeper(CONNECTADDRESS, SESSIONTIME, new Watcher() {
            public void process(WatchedEvent event) {
                //增加或者删除的时候才会触发NodeChildrenChanged
                if (event.getType()== Event.EventType.NodeChildrenChanged && event.getPath().equals(PATH)){
                   showChildrenNode(PATH);
                }else{
                    showChildrenNode("/");
                }
            }
        });
    }

    private static void showChildrenNode(String path) {
        List<String> list=null;
        try{//设置为true，就是使用创建连接时实现监听的那个方法，如果是new的话，就会使用新创建的监听
            //知道为啥会重复监听了，是因为一直在调用list=zk.getChildren(path,true);
            list=zk.getChildren(path,true);
            System.out.println("*************"+list);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    @Test
    public void test() throws Exception {
        MyWatcher1 watcher = new MyWatcher1();
        MyWatcher1.setZk(watcher.start());
        Thread.sleep(Integer.MAX_VALUE);
    }

}
